using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class RayToScreenMid : MonoBehaviour
{
    // 从视角摄像机向鼠标点击位置发射射线和子弹

    Camera mainCamera;                // 主摄像机
    public RawImage rawImage;         // 用于指示射击方向的RawImage
    public Text scoreText;            // 用于显示分数的文本
    public float moveSpeed = 5f;      // 玩家移动速度
    public float bulletSpeed = 15f;   // 子弹速度
    public float bulletSize = 0.2f;   // 子弹大小
    public GameObject bulletPrefab;   // 子弹预制体
    private float score = 0f;         // 当前分数

    [Header("靶盘设置")]
    public Transform targetCenter;    // 靶盘中心点
    public float targetSize = 3f;     // 靶盘整体大小
    public int ringCount = 8;         // 圆环数量（增加到8个不同区域）
    public float centerHoleSize = 0.3f; // 中心空洞大小
    
    [Header("靶盘默认位置和旋转")]
    public Vector3 defaultPosition = new Vector3(1.67f, -2.11f, 2.19f); // 靶盘默认位置
    public Vector3 defaultRotation = new Vector3(-99.4f, -0.26f, -2f);  // 靶盘默认旋转
    
    [Header("翻转设置")]
    public float flipDuration = 0.5f; // 翻转持续时间
    public AnimationCurve flipCurve = AnimationCurve.EaseInOut(0f, 0f, 1f, 1f); // 翻转曲线
    
    [Header("区域颜色和分数设置")]
    public Color[] zoneColors = new Color[] {
        Color.white,      // 外环 (10分)
        Color.grey,       // 第2环 (20分)
        Color.blue,       // 第3环 (30分)
        Color.cyan,       // 第4环 (40分)
        Color.green,      // 第5环 (50分)
        Color.yellow,     // 第6环 (60分)
        Color.magenta,    // 第7环 (70分)
        Color.red         // 中心 (80分)
    };
    
    public int[] zoneScores = new int[] {
        10, 20, 30, 40, 50, 60, 70, 80
    };
    
    private List<GameObject> targetRings = new List<GameObject>(); // 存储所有圆环
    private List<GameObject> bulletsOnTarget = new List<GameObject>(); // 存储嵌入靶盘的子弹
    private bool isFlipping = false; // 是否正在翻转
    private Quaternion startRotation; // 翻转起始旋转
    private Quaternion targetRotation; // 翻转目标旋转
    private float flipProgress = 0f; // 翻转进度
    
    private void Start()
    {
        mainCamera = Camera.main;
        rawImage = Instantiate(Resources.Load<RawImage>("RawImage"), GameObject.Find("Canvas").transform);
        
        // 如果未指定targetCenter，自动创建一个
        if (targetCenter == null)
        {
            GameObject centerObj = new GameObject("TargetCenter");
            targetCenter = centerObj.transform;
        }
        
        // 设置targetCenter的位置和旋转
        targetCenter.position = defaultPosition;
        targetCenter.rotation = Quaternion.Euler(defaultRotation);
        
        // 生成圆形靶盘
        CreateTarget();
    }

    void Update()
    {
        // 更新rawImage位置，使其跟随鼠标
        Vector3 mousePos = Input.mousePosition;
        rawImage.transform.position = mousePos;
        
        // 玩家移动控制
        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        var movement = new Vector3(h, 0, v) * Time.deltaTime * moveSpeed;
        
        if (h != 0 || v != 0)
        {
            transform.LookAt(transform.position + movement);
            transform.Translate(movement);
        }
        
        // 处理翻转逻辑
        if (isFlipping)
        {
            flipProgress += Time.deltaTime / flipDuration;
            float curveProgress = flipCurve.Evaluate(flipProgress);
            targetCenter.rotation = Quaternion.Slerp(startRotation, targetRotation, curveProgress);
            
            if (flipProgress >= 1f)
                isFlipping = false;
        }
        
        // 射击逻辑（左键点击）
        if (Input.GetMouseButtonDown(0))
        {
            FireBullet();
        }
        
        // 翻转逻辑（右键点击）
        if (Input.GetMouseButtonDown(1))
        {
            RaycastHit hit;
            Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
            
            if (Physics.Raycast(ray, out hit))
            {
                // 检查是否击中靶盘区域
                if (hit.transform.CompareTag("TargetZone"))
                {
                    // 开始翻转靶盘
                    StartFlip(hit.point);
                }
            }
        }
        
        // 更新分数显示
        scoreText.text = "分数: " + score.ToString();
    }

    // 开始翻转靶盘
    private void StartFlip(Vector3 hitPoint)
    {
        if (isFlipping) return;
        
        // 计算翻转轴（从靶盘中心到点击点的方向）
        Vector3 flipAxis = (hitPoint - targetCenter.position).normalized;
        
        // 设置翻转起始和目标旋转
        startRotation = targetCenter.rotation;
        targetRotation = Quaternion.AngleAxis(180f, flipAxis) * startRotation;
        
        // 重置翻转进度
        flipProgress = 0f;
        isFlipping = true;
    }

    // 创建圆形靶盘
    private void CreateTarget()
    {
        // 清除旧的靶盘
        foreach (GameObject ring in targetRings)
            Destroy(ring);
        targetRings.Clear();
        
        // 清除旧的子弹
        foreach (GameObject bullet in bulletsOnTarget)
            Destroy(bullet);
        bulletsOnTarget.Clear();
        
        // 计算每个环的宽度
        float ringWidth = (targetSize - centerHoleSize) / ringCount;
        
        // 创建每个环
        for (int i = 0; i < ringCount; i++)
        {
            float innerRadius = centerHoleSize + i * ringWidth;
            float outerRadius = innerRadius + ringWidth;
            
            GameObject ring = CreateRing(innerRadius, outerRadius, i);
            ring.name = "Zone_" + i;
            
            // 设置标签为TargetZone
            ring.tag = "TargetZone";
            
            // 设置环的位置和旋转与targetCenter一致
            ring.transform.parent = targetCenter;
            ring.transform.localPosition = Vector3.zero;
            ring.transform.localRotation = Quaternion.identity;
            ring.transform.localScale = Vector3.one;
            
            targetRings.Add(ring);
        }
    }

    // 创建单个圆环
    private GameObject CreateRing(float innerRadius, float outerRadius, int ringIndex)
    {
        GameObject ring = new GameObject("Zone_" + ringIndex);
        
        // 添加碰撞体
        MeshCollider collider = ring.AddComponent<MeshCollider>();
        collider.sharedMesh = CreateRingMesh(innerRadius, outerRadius);
        collider.convex = true;
        
        // 添加渲染组件
        MeshRenderer renderer = ring.AddComponent<MeshRenderer>();
        MeshFilter filter = ring.AddComponent<MeshFilter>();
        filter.mesh = collider.sharedMesh;
        
        // 设置材质（使用配置的颜色）
        Material material = new Material(Shader.Find("Standard"));
        
        // 确保索引不越界
        if (ringIndex < zoneColors.Length)
            material.color = zoneColors[ringIndex];
        else
            material.color = Color.gray;
            
        renderer.material = material;
        
        // 添加自定义分数数据
        TargetZone zone = ring.AddComponent<TargetZone>();
        zone.zoneIndex = ringIndex;
        zone.points = ringIndex < zoneScores.Length ? zoneScores[ringIndex] : 10;
        
        return ring;
    }

    // 创建环形网格
    private Mesh CreateRingMesh(float innerRadius, float outerRadius)
    {
        Mesh mesh = new Mesh();
        
        int segments = 36;
        Vector3[] vertices = new Vector3[(segments + 1) * 2];
        Vector2[] uv = new Vector2[(segments + 1) * 2];
        int[] triangles = new int[segments * 6];
        
        // 生成顶点和UV
        for (int i = 0; i <= segments; i++)
        {
            float angle = (float)i / segments * Mathf.PI * 2;
            float x = Mathf.Cos(angle);
            float z = Mathf.Sin(angle);
            
            // 外环顶点
            vertices[i] = new Vector3(x * outerRadius, 0, z * outerRadius);
            uv[i] = new Vector2((float)i / segments, 1);
            
            // 内环顶点
            vertices[i + segments + 1] = new Vector3(x * innerRadius, 0, z * innerRadius);
            uv[i + segments + 1] = new Vector2((float)i / segments, 0);
        }
        
        // 生成三角形
        for (int i = 0; i < segments; i++)
        {
            int index = i * 6;
            triangles[index] = i;
            triangles[index + 1] = i + segments + 1;
            triangles[index + 2] = i + 1;
            triangles[index + 3] = i + 1;
            triangles[index + 4] = i + segments + 1;
            triangles[index + 5] = i + segments + 2;
        }
        
        mesh.vertices = vertices;
        mesh.uv = uv;
        mesh.triangles = triangles;
        mesh.RecalculateNormals();
        
        return mesh;
    }

    private void FireBullet()
    {
        // 从鼠标位置发射射线，检测目标
        Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        
        // 创建子弹
        GameObject bullet = Instantiate(bulletPrefab);
        bullet.transform.position = transform.position + Vector3.up; // 从玩家位置上方发射
        bullet.transform.localScale = Vector3.one * bulletSize;
        
        Vector3 targetPoint;
        bool hitTarget = false;
        int points = 0;
        
        // 检测射线是否击中物体
        if (Physics.Raycast(ray, out hit))
        {
            targetPoint = hit.point;
            
            // 检查是否击中靶盘区域
            if (hit.transform.CompareTag("TargetZone"))
            {
                Debug.Log("射线检测到物体: " + hit.transform.name);
                hitTarget = true;
                
                // 获取击中区域的分数
                TargetZone zone = hit.transform.GetComponent<TargetZone>();
                if (zone != null)
                {
                    points = zone.points;
                    score += points;
                    Debug.Log($"击中区域 {zone.zoneIndex}! +{points} 分");
                    
                    // 显示击中特效（使用击中区域的颜色）
                    ShowHitEffect(hit.point, zone.zoneIndex);
                }
            }
        }
        else
        {
            // 如果没有击中任何物体，子弹朝射线方向发射一段距离
            targetPoint = ray.origin + ray.direction * 100;
        }
        
        // 让子弹朝向目标点
        bullet.transform.LookAt(targetPoint);
        
        // 添加子弹移动逻辑
        Rigidbody bulletRb = bullet.GetComponent<Rigidbody>();
        if (bulletRb != null)
        {
            bulletRb.velocity = bullet.transform.forward * bulletSpeed;
            
            // 如果击中靶盘，子弹嵌入后保持在靶盘上
            if (hitTarget)
            {
                StartCoroutine(EmbedBulletIntoTarget(bullet, hit.transform, hit.point, hit.normal));
            }
            else
            {
                // 未击中靶盘，子弹一段时间后销毁
                Destroy(bullet, 3f);
            }
        }
    }

    // 子弹嵌入靶盘的协程
    private IEnumerator EmbedBulletIntoTarget(GameObject bullet, Transform target, Vector3 hitPoint, Vector3 hitNormal)
    {
        Rigidbody bulletRb = bullet.GetComponent<Rigidbody>();
        
        // 等待子弹到达击中位置
        while (Vector3.Distance(bullet.transform.position, hitPoint) > 0.1f)
        {
            yield return null;
        }
        
        // 禁用子弹的物理模拟
        if (bulletRb != null)
        {
            bulletRb.isKinematic = true;
            bulletRb.useGravity = false;
        }
        
        // 将子弹位置调整到击中位置，并使其方向与击中表面法线一致
        bullet.transform.position = hitPoint;
        bullet.transform.rotation = Quaternion.LookRotation(-hitNormal);
        
        // 将子弹设为靶盘的子物体，使其跟随靶盘移动和旋转
        bullet.transform.parent = target;
        
        // 记录嵌入的子弹
        bulletsOnTarget.Add(bullet);
    }
    
    // 显示击中特效
    private void ShowHitEffect(Vector3 position, int zoneIndex)
    {
        // 创建一个临时的击中特效对象
        GameObject hitEffect = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        hitEffect.transform.position = position;
        hitEffect.transform.localScale = Vector3.one * 0.3f;
        
        // 使用对应区域的颜色
        Color effectColor = Color.white;
        if (zoneIndex < zoneColors.Length)
            effectColor = zoneColors[zoneIndex];
            
        hitEffect.GetComponent<Renderer>().material.color = effectColor;
        
        // 2秒后销毁特效
        Destroy(hitEffect, 2f);
    }
}

// 靶盘区域数据类
public class TargetZone : MonoBehaviour
{
    public int zoneIndex;  // 区域索引
    public int points;     // 区域对应的分数
}